package com.ruoyi.iot.websocket;

import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.iot.websocket.message.WebSocketMessage;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket处理类
 */
@ServerEndpoint("/websocket/iot/{deviceId}")
@Component
public class IotWebSocket {
    private static final Logger log = LoggerFactory.getLogger(IotWebSocket.class);

    /**
     * 连接集合
     */
    private static ConcurrentHashMap<String, IotWebSocket> deviceWebSocketMap = new ConcurrentHashMap<>();
    
    /**
     * 设备信息集合
     */
    private static ConcurrentHashMap<String, Object> deviceInfoMap = new ConcurrentHashMap<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 设备ID
     */
    private String deviceId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
        this.session = session;
        this.deviceId = deviceId;
        if (deviceWebSocketMap.containsKey(deviceId)) {
            deviceWebSocketMap.remove(deviceId);
            deviceWebSocketMap.put(deviceId, this);
        } else {
            deviceWebSocketMap.put(deviceId, this);
        }
        log.info("设备[{}]连接成功，当前在线设备数为:{}", deviceId, deviceWebSocketMap.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (deviceWebSocketMap.containsKey(deviceId)) {
            deviceWebSocketMap.remove(deviceId);
            deviceInfoMap.remove(deviceId);
            log.info("设备[{}]退出，当前在线设备数为:{}", deviceId, deviceWebSocketMap.size());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("设备[{}]发送消息:{}", deviceId, message);
        try {
            WebSocketMessage wsMessage = JSON.parseObject(message, WebSocketMessage.class);
            handleMessage(wsMessage);
        } catch (Exception e) {
            log.error("消息处理异常:", e);
        }
    }

    /**
     * 处理消息
     */
    private void handleMessage(WebSocketMessage message) {
        switch (message.getType()) {
            case "deviceInfo":
                // 保存设备信息
                deviceInfoMap.put(deviceId, message.getData());
                break;
            case "scriptStatus":
                // 处理脚本状态更新
                log.info("设备[{}]脚本状态更新:{}", deviceId, message.getData());
                break;
            case "screenshot":
                // 处理截图数据
                log.info("设备[{}]发送截图数据", deviceId);
                break;
            case "heartbeat":
                // 处理心跳
                handleHeartbeat(message);
                break;
            default:
                log.warn("未知消息类型:{}", message.getType());
        }
    }

    /**
     * 处理心跳消息
     */
    private void handleHeartbeat(WebSocketMessage message) {
        try {
            // 更新设备状态
            Map<String, Object> heartbeatData = (Map<String, Object>) message.getData();
            deviceInfoMap.computeIfPresent(deviceId, (key, oldValue) -> {
                if (oldValue instanceof Map) {
                    ((Map<String, Object>) oldValue).putAll(heartbeatData);
                }
                return oldValue;
            });
            
            // 发送心跳响应
            WebSocketMessage response = new WebSocketMessage();
            response.setType("heartbeat");
            sendMessage(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("心跳处理异常:", e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("设备[{}]连接异常:{}", this.deviceId, error.getMessage());
    }

    /**
     * 发送消息
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("消息发送异常:", e);
        }
    }

    /**
     * 发送消息到指定设备
     */
    public static void sendMessageToDevice(String deviceId, WebSocketMessage message) {
        try {
            IotWebSocket webSocket = deviceWebSocketMap.get(deviceId);
            if (webSocket != null) {
                webSocket.sendMessage(JSON.toJSONString(message));
            } else {
                log.error("设备[{}]不在线！", deviceId);
            }
        } catch (Exception e) {
            log.error("发送消息到设备异常:", e);
        }
    }

    /**
     * 获取设备信息
     */
    public static Object getDeviceInfo(String deviceId) {
        return deviceInfoMap.get(deviceId);
    }

    /**
     * 获取所有在线设备
     */
    public static ConcurrentHashMap<String, Object> getAllDeviceInfo() {
        return deviceInfoMap;
    }

    /**
     * 运行脚本
     */
    public static void runScript(String deviceId, String scriptName, String scriptCode) {
        WebSocketMessage message = new WebSocketMessage();
        message.setType("runScript");
        Map<String, String> data = new ConcurrentHashMap<>();
        data.put("name", scriptName);
        data.put("code", scriptCode);
        message.setData(data);
        sendMessageToDevice(deviceId, message);
    }

    /**
     * 停止脚本
     */
    public static void stopScript(String deviceId) {
        WebSocketMessage message = new WebSocketMessage();
        message.setType("stopScript");
        sendMessageToDevice(deviceId, message);
    }

    /**
     * 请求截图
     */
    public static void requestScreenshot(String deviceId) {
        WebSocketMessage message = new WebSocketMessage();
        message.setType("getScreenshot");
        sendMessageToDevice(deviceId, message);
    }
} 